#include "aa_neighborhood.h"
#include "../m_tree/mTreeNode.h"
#include "aa_util.h"
#include "../pdb_index/atom.h"
#include <string.h>
#include <sys/timeb.h>

#include "../bulk_storage/bulk_storage.h"

void calc_neighborhoods_new(char * pdbCode, double neighborhoodRadius,
			    struct store * atomStore, struct mTree * atomTree,
			    struct store * neighStore, struct mTree * neighTree);


// Write a backup out once every two hours.
#define SYNC_INTERVAL 7200

int main(int argc, char** argv) {
  time_t last_sync, now;
  struct timeb ts;

  struct store * atomStore, * neighStore;
  struct mTree * atomTree,  * neighTree;

  char * neigh_base = argv[1];
  char * neigh_fat, * neigh_tree, * neigh_tree_fat;

  char * atom_base;
  int first = 0;
  int i;

  if(argc != 2 && argc != 3) {
    printf("Usage: ./index_many_neighborhoods_new neighborhood_store [recovery_filename]\n   Pipe the atom store base names into STDIN.\nThe recovery_filename option is the filename output by the last successful periodic backup.  To recover from a crash, copy the last good incremental backup to location of neighborhood store, and pass in a recovery filename.  sizeof(neighborhood) = %ld, sizeof(mTreeNode) = %ld\n", 
	   (long) sizeof(struct aa_neighborhood), (long) sizeof(struct mTreeNode));
    //  printf("Using these files for tree: %s, %s, %s, %s  sizeof(aa_neighborhood) = %ld\n", neigh_base, neigh_fat, neigh_tree, neigh_tree_fat, (long)sizeof(struct aa_neighborhood));
    return 1;
  }

  neigh_fat = malloc(sizeof(char) * (strlen(neigh_base) + 4 + 1));
  neigh_tree = malloc(sizeof(char) * (strlen(neigh_base) + 6 + 1));
  neigh_tree_fat = malloc(sizeof(char) * (strlen(neigh_base) + 10 + 1));

  strcpy(neigh_fat,      neigh_base);
  strcpy(neigh_tree,     neigh_base);
  strcpy(neigh_tree_fat, neigh_base);

  strcat(neigh_fat,      ".fat");
  strcat(neigh_tree,     ".mTree");
  strcat(neigh_tree_fat, ".mTree.fat");
  
  printf("Using these files for tree: %s, %s, %s, %s  sizeof(aa_neighborhood) = %ld\n", neigh_base, neigh_fat, neigh_tree, neigh_tree_fat, (long)sizeof(struct aa_neighborhood));
  fflush(stdout);
  
  neighStore = store_open_cached(neigh_base, neigh_fat, sizeof(struct aa_neighborhood), 100, 20500000);
  neighTree  = mTree_open_cached(neighStore, neigh_tree, neigh_tree_fat, 8000000, (double(*)(const void*,const void*))&aa_neigh_dist);
  
  i = 0;

  ftime(&ts);

  last_sync = ts.time;

    
  if(argc == 3) {
    while(EOF != scanf("%as\n", &atom_base)) {
      if (!strcmp(atom_base, argv[2])) {
	break;
      }
      printf("skipping %s\n", atom_base);
    }
    first = 1; // first = 1 => atom_base already contains the first file name.
  }


  while(first || EOF != scanf("%as\n", &atom_base)) {
    //  for(i = 2; i < argc; i++) {

    //    char * atom_base = argv[i];
    char * atom_fat, * atom_tree, * atom_tree_fat;

    first =0;

    ftime(&ts);

    now = ts.time;

    if(now - last_sync > SYNC_INTERVAL) {
      printf("Running disk sync and backup.\n");
      //      mTree_verify(neighTree);
      //      printf("Tree integrity verified.\n");
      printf("Skipping tree integrity check...\n");
      printf("Check for 'Backup complete.' after this line.\nIf it's missing, use the tilde copies of the backup files, and the\nrecovery_filename from the backup message before this one.\nrecovery_filename = %s\n", atom_base);
      fflush(stdout);

      fsync(((struct cacheStore *)neighTree->nStore->store_p)->fileStore->fat_file);
      fsync(((struct cacheStore *)neighTree->nStore->store_p)->fileStore->data_file);
      fsync(((struct cacheStore *)neighTree->oStore->store_p)->fileStore->fat_file);
      fsync(((struct cacheStore *)neighTree->oStore->store_p)->fileStore->data_file);

      printf("Flushed file buffers of working copy to disk.\n");


      if(! (cs_dumpBackup(neighTree->nStore->store_p, "node_backup", "node_backup.fat") && 
	    cs_dumpBackup(neighTree->oStore->store_p, "object_backup", "object_backup.fat"))) {
	printf("Backup failed!\n");
	printf("Attempting clean shutdown.");
	fflush(stdout);
	mTree_close(neighTree);
	store_close(neighStore);
	printf("Shutdown complete-If the line above this one reads 'Attempting clean shutdown',  then everything should be OK.\n");
	fflush(stdout);
	return 1;
      }

      printf("Backup complete.\n");
      fflush(stdout);
      ftime(&ts);
      last_sync = ts.time;

    }


    i++;

    printf("%s ", atom_base);
    printf("(%.4s)\n", &(atom_base[strlen(atom_base)-10]));
    fflush(stdout);

    atom_fat = malloc(sizeof(char) * (strlen(atom_base) + 4 + 1));
    atom_tree = malloc(sizeof(char) * (strlen(atom_base) + 6 + 1));
    atom_tree_fat = malloc(sizeof(char) * (strlen(atom_base) + 10 + 1));

    strcpy(atom_fat,      atom_base);
    strcpy(atom_tree,     atom_base);
    strcpy(atom_tree_fat, atom_base);

    strcat(atom_fat,      ".fat");
    strcat(atom_tree,     ".mTree");
    strcat(atom_tree_fat, ".mTree.fat");

    atomStore  = store_open_cached(atom_base, atom_fat, sizeof(struct atom), 100, 120000);
    atomTree   = mTree_open_cached(atomStore, atom_tree, atom_tree_fat, 80000, (double(*)(const void*,const void*))&atom_distance);


    calc_neighborhoods_new(&(atom_base[strlen(atom_base)-10]), 30 * 1000, atomStore, atomTree, neighStore, neighTree);

    mTree_close(atomTree);
    store_close(atomStore);

    if(i % 10 == 0) {
      printf("Neighborhood tree stats:\n");
      mTree_printStats(neighTree);

    }

    free(atom_fat);
    free(atom_tree);
    free(atom_tree_fat);


  }


  mTree_close(neighTree);
  store_close(neighStore);

  free(neigh_fat);
  free(neigh_tree);
  free(neigh_tree_fat);

  return 0;

}

void calc_neighborhoods_new(char * pdbCode, double neighborhoodRadius,
			struct store * atomStore, struct mTree * atomTree,
			struct store * neighStore, struct mTree * neighTree) {
  off_t i = 1;

  struct atom * a = store_read(atomStore, i);

  while(a->name[0] != 0) {
    off_t start, stop;
    
    store_release(atomStore, i);

    if(aa_neigh_can_calc_neighborhood(atomStore, i)) {
      off_t n_idx = store_new(neighStore);
      struct aa_neighborhood * neigh = store_read(neighStore, n_idx);

      //      printf("%d -- \n", (int) i);
      
      //    double aa_neigh_dist(const struct aa_neighborhood* n1, const struct aa_neighborhood* n2);
      
      aa_neigh_init(neigh, pdbCode, atomStore, atomTree, i);
      
      store_write(neighStore, n_idx);
      
      mTree_insert(neighTree, n_idx);
      
      store_release(neighStore, n_idx);
      
      
    }

    find_aa_range(atomStore, i, &start, &stop);
    
    i = stop + 1;
    
    a = store_read(atomStore, i);

  }
  store_release(atomStore, i);

}
